package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        Employee employee = (Employee) request.getSession().getAttribute("USER_IN_SESSION");
        Employee employee = UserContext.getCurrentUser();
        //判断是否超管,是的话直接放行
        if (employee.isAdmin()) {
            return true;
        }
        //handler如果是handlerMethod类型,代表拦截的就是处理方法
        if (handler instanceof HandlerMethod) {
            //如果是则强转
            HandlerMethod method = (HandlerMethod) handler;
            //从方法上获取注解
            RequiredPermission annotation = method.getMethodAnnotation(RequiredPermission.class);
            //判断该方法是否有贴注解
            if (annotation == null) {
                return true;
            }
            //获取当前登录用户拥有的权限
            //List<String> permissions = (List<String>) request.getSession().getAttribute("EXPRESSION_IN_SESSION");
            List<String> expressions = UserContext.getExpressions();
            //获取权限注解中的表达式
            String expression = annotation.expression();
            if (!expressions.contains(expression)) {
                response.sendRedirect("/nopermission");
                return false;
            }
            //判断该用户的权限是否包含此方法的权限
        }
        return true;
    }
}
